<!-- 单张图片上传组件 -->
<template>
  <div>
    <el-upload
      class="uploader"
      action="/"
      :on-change="image.choose"
      list-type="picture"
      :auto-upload="false"
      :show-file-list="false"
    >
      <img v-if="image.file" :src="image.url" />
      <i v-else class="el-icon-plus uploader-icon"></i>
    </el-upload>
  </div>
</template>

<script setup>
import { reactive, watch } from "vue"
const props = defineProps({
    file: {
        type: Object || String,
        default: () => {},
    },
    size: {
        type: String,
        default: "100px",
    },
})
watch(
    [() => props.file],
    [
        () => {
            if (typeof props.file === "string") {
                image.file = props.file
                image.url = props.file
            }
        },
    ]
)

const emit = defineEmits(["update:file"])
const image = reactive({
    file: "",
    url: "",
    choose(e) {
        image.url = e.url
        image.file = e.raw
        emit("update:file", image.file)
    },
})
</script>

<style lang="scss" scoped>
.el-upload {
    width: v-bind(size);
    height: v-bind(size);
}
.uploader {
    width: 100%;
    height: 100%;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    .uploader-icon {
        width: 100%;
        height: 100%;
        font-size: 28px;
        color: #8c939d;
        display: flex;
        justify-content: center;
        align-items: center;
    }
    img {
        width: v-bind(size);
        height: v-bind(size);
        display: block;
    }
}
:deep(.el-upload, .el-upload--picture) {
    width: 100%;
    height: 100%;
}
.uploader:hover {
    border-color: var(--el-color-primary);
    .uploader-icon {
        color: var(--el-color-primary);
    }
}
</style>
>
